package cn.lin.handler;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author cn.Lin
 * @create 2024-12-05-0:54
 */
@Component
public class SignInWebSocketHandler extends TextWebSocketHandler {

    private final static Map<Integer, WebSocketSession> userSessions = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        // 从URL参数中获取用户ID
        String query = session.getUri().getQuery();
        Integer userId = extractUserIdFromQuery(query);

        if (userId != null) {
            session.getAttributes().put("userId", userId);
            userSessions.put(userId, session);
        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println(message.getPayload());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        Integer userId = getUserIdFromSession(session);
        if (userId != null) {
            userSessions.remove(userId);
        }
    }

    /**
     * 通知特定学生进行签到
     */
    public void notifyStudent(Integer stuId) {
        WebSocketSession session = userSessions.get(stuId);
        if (session != null && session.isOpen()) {
            try {
                session.sendMessage(new TextMessage("startSignIn"));
            } catch (IOException e) {
                throw new RuntimeException("Failed to send sign in notification", e);
            }
        }
    }

    private Integer getUserIdFromSession(WebSocketSession session) {
        // 从session中获取用户ID的实现
        return (Integer) session.getAttributes().get("userId");
    }

    private Integer extractUserIdFromQuery(String query) {
        if (query != null && query.contains("userId=")) {
            String userId = query.split("userId=")[1];
            try {
                return Integer.parseInt(userId);
            } catch (NumberFormatException e) {
                return null;
            }
        }
        return null;
    }
}
